<script lang="ts" setup>
import { computed, h, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, message, Space, Spin } from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import { getGroupList } from '#/api/admin'
import { getSupplyList } from '#/api/common'
import { AdminGoodsCategory } from '#/api/spuBom'
import { supplyDetails, supplyUserAdd, supplyUserEdit, supplyUserInfo } from '#/api/supplyUser'

const emit = defineEmits(['refresh'])
const GoodsCategory = ref<any>([])
const groupArr = ref<any>([])

const idsArr: any = ref([])
const inputDisabled = ref(true)

const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})

const keyword = ref('')
const keyword1 = ref('')
const fetching = ref(false)
// 先写一个 computed
const passwordRules = computed(() => (inputDisabled.value ? undefined : 'required'))
async function fetchRemoteOptions({ keyword = '' }: Record<string, any>) {
  let quick_search = ''
  let initValue = ''
  const initKey = 'supply.id'
  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
    if (initValue) {
      initValue = keyword.replace('initValue:', '').split(',')
    }
  } else {
    quick_search = keyword
  }
  const { list } = await getSupplyList({
    quick_search,
    page: 1,
    limit: 999,
    initKey,
    initValue,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

async function fetchRemoteOptions1({ keyword = '' }: Record<string, any>) {
  let quick_search = ''
  let initValue = ''
  const initKey = 'supply.id'
  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
    if (initValue) {
      initValue = keyword.replace('initValue:', '').split(',')
    }
  } else {
    quick_search = keyword
  }
  const { list } = await getSupplyList({
    quick_search,
    page: 1,
    limit: 999,
    initKey,
    initValue,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'ApiSelect',
      // 对应组件的参数
      disabled: inputDisabled,
      componentProps: () => {
        return {
          api: fetchRemoteOptions,
          // 禁止本地过滤
          filterOption: false,

          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword1.value = value
          }, 300),

          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword1.value || undefined,
          },
          showSearch: true,
          allowClear: true,
          immediate: false,
          alwaysLoad: true,
          visibleEvent: 'onFocus',
          onChange: (value: any) => {
            supplyDetails({ id: value }).then((res: any) => {
              console.log(res)
              if (res) {
                baseFormApi.setValues({ supply_name: res.SupplyNa }, false)
                baseFormApi.setValues({ username: res.SupplyCode }, false)
              }
            })
          },
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword1.value = ''
          },
        }
      },
      // 字段名
      fieldName: 'supply_id',
      // 界面显示的label
      label: '关联供货商',
      rules: 'required',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '供货商名称',
      },
      fieldName: 'supply_name',
      label: '供货商名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '登录账号',
        disabled: inputDisabled,
      },
      fieldName: 'username',
      label: '登录账号',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '为空不修改',
      },
      fieldName: 'password',
      label: '登录密码',
      rules: passwordRules,
    },
    {
      component: 'Switch',
      fieldName: 'status',
      label: '启用',
      defaultValue: '1',
      componentProps: {
        class: 'w-[50px]',
        checkedValue: '1',
        unCheckedValue: '0',
      },
    },
    {
      component: 'RadioGroup',
      defaultValue: 0,
      componentProps: {
        options: [
          {
            label: '供货商账号',
            value: 0,
          },
          {
            label: '管理员账号',
            value: 1,
          },
        ],
      },
      fieldName: 'is_admin',
      label: '账号类型',
    },
    {
      component: 'ApiSelect',
      // 对应组件的参数
      componentProps: () => {
        return {
          api: fetchRemoteOptions1,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value = value
          }, 300),

          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value || undefined,
          },
          showSearch: true,
          allowClear: true,
          immediate: false,
          mode: 'multiple',
          alwaysLoad: true,
          visibleEvent: 'onFocus',

          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value = ''
          },
        }
      },
      // 字段名
      fieldName: 'auth_id',
      // 界面显示的label
      label: '账号权限',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
  ],
  wrapperClass: 'grid-cols-1',
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[45%] h-[60%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      const parmas = {
        is_select: true,
        page: 1,
        initKey: 'id',
        select: true,
      }
      AdminGoodsCategory(parmas).then((res: any) => {
        GoodsCategory.value = res.list.map((item) => ({
          label: item.name,
          value: item.id,
        }))
      })

      const parmas1 = {
        isTree: true,
        page: 1,
        absoluteAuth: 1,
        initKey: 'id',
        select: true,
      }
      getGroupList(parmas1).then((res: any) => {
        groupArr.value = res.options.map((item) => ({
          label: item.name,
          value: item.id,
        }))
      })

      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }
    }
  },
})

async function initData(rowData: any) {
  supplyUserInfo({ id: rowData }).then(async (response) => {
    const row = response.row
    await baseFormApi.setValues(row, false)
    keyword1.value = `initValue:${response.row.supply_id}`
    keyword.value = `initValue:${response.row.auth_id}`
  })
}

// 保存
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) {
    return
  }
  const values = await baseFormApi.getValues()
  const parmas = {
    ...values,
  }
  if (values.id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      supplyUserEdit(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      supplyUserEdit(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    supplyUserAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm />

    <div style="margin-left: 20px">
      说明：
      <p><span class="red">关联供货商：</span> 打印合格证时，直接显示供货商的编号；如果为空，默认供货商编号为货品的默认供货商</p>
      <p><span class="red">账号权限：</span> 供货商能查看采购单的权限</p>
      <p><span class="red">管理员账号：</span>可查看全平台的采购单和货品信息</p>
    </div>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
.red {
  color: red;
}
</style>
